package udp

import (
	"log"
	"net"
	"screenRobot/network"
)

// Client 客户端
func Client(addrChan chan *net.UDPAddr) {
	log.Println("执行了")
	//解析地址
	addr, err := net.ResolveUDPAddr("udp", ":6970")
	if network.Handler("解析地址异常", err) {
		return
	}

	//创建监听
	conn, err := net.ListenUDP("udp", addr)
	if network.Handler("解析地址异常", err) {
		return
	}

	defer conn.Close()

	buffer := make([]byte, 1024)
	count := 0
	for {
		n, addr, err := conn.ReadFromUDP(buffer)

		if network.Handler("读取数据异常", err) {
			continue
		}
		log.Printf("监听到来自%s的数据：%s\n", addr, string(buffer[:n]))

		if string(buffer[:n]) != "dpengchen@163.com" {
			continue
		}

		//设置服务端的监听端口
		addr.Port = 6970
		_, err = conn.WriteToUDP([]byte("dpengchen@163.com"), addr)
		if network.Handler("发送信息异常", err) {
			continue
		}

		if count < 3 {
			count++
			continue
		}
		//设置返回的是tcp端口
		addr.Port = 9700
		addrChan <- addr
		break
	}

}
